package leetcode.code0134;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

/**
 * 贪心 <br>
 *
 * 最大连续攒气儿区间的开头<br>
 *
 * 执行用时：3 ms, 在所有 Java 提交中击败了23.71%的用户
 *
 * 内存消耗：58.2 MB, 在所有 Java 提交中击败了78.30%的用户
 *
 * 通过测试用例：35 / 35
 */
public class Solution implements IDebug {

	public int canCompleteCircuit(int[] gas, int[] cost) {
		int allGas = 0;
		int allCost = 0;
		int len = gas.length;
		int[] diff = new int[len];
		for (int i = 0; i < len; i++) {
			allGas += gas[i];
			allCost += cost[i];
			diff[i] = gas[i] - cost[i];
		}
		if (allCost > allGas) {
			return -1;
		}
		if (len == 1) {
			if (diff[0] >= 0) {
				return 0;
			} else {
				return -1;
			}
		}
		int start = 0;
		int sum = 0;
		int max = 0;
		int ans = -1;
		int p = 0;
		boolean flag = false;
		while (p < len << 1) {
			int index = p % len;
			int last = (p + len - 1) % len;
			if (diff[index] > 0 && diff[last] < 0) {
				if (sum >= max) {
					ans = start;
				}
				start = index;
				sum = 0;
				flag = true;
			}
			if (flag) {
				sum += diff[index];
			}
			p++;
		}
		return ans;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(3, this.canCompleteCircuit(HelpDebug.str2array3("[1,2,3,4,5]"), HelpDebug.str2array3("[3,4,5,1,2]")));

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub
		HelpDebug.compare(3, this.canCompleteCircuit(HelpDebug.str2array3("[5,8,2,8]"), HelpDebug.str2array3("[6,5,6,6]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub
		HelpDebug.compare(-1, this.canCompleteCircuit(HelpDebug.str2array3("[4]"), HelpDebug.str2array3("[5]")));

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub
		HelpDebug.compare(0, this.canCompleteCircuit(HelpDebug.str2array3("[5]"), HelpDebug.str2array3("[4]")));

	}

	public static void main(String[] args) {
		Solution so = new Solution();
//		so.debug1();
//		so.debug2();
//		so.debug3();
		so.debug4();

	}

}
